require 'net/pop3_ssl'

module UnfuddleMyEmail
  # Fetcher iterates through all emails in the given POP3 mailbox and
  # yields each one, optionally deleting the message after yield. The
  # message yielded is an instance of TmailAdapter.
  #
  # Example:
  #
  #   fetch = Fetcher.new('pop.example.com',995,true,'username','password',false)
  #   fetcher.each do |message|
  #     puts message.subject
  #   end
  #
  #   # Enumerable is included so you can use those features (except for sort,min,max) as well:
  #   fetcher.to_a # => [#<TmailAdapter instance>]
  class Fetcher
    def initialize(server, port, ssl, username, password, delete=false)
      @pop3_server        = server
      @pop3_port          = port
      @pop3_ssl           = ssl
      @pop3_username      = username
      @pop3_password      = password
      @pop3_delete        = delete
    end

    def each
      if @pop3_ssl
        Net::POP3.enable_ssl(OpenSSL::SSL::VERIFY_NONE)
      end
      Net::POP3.start(@pop3_server, @pop3_port, @pop3_username, @pop3_password) do |pop|
        pop.each_mail { |message|
          mail_item = TmailAdapter.new(message.pop)
          yield mail_item
          message.delete if @pop3_delete
        }
      end
    end
    include Enumerable
  end
end
